const React = require('react');
const {
  View,
  StyleSheet,
} = require('react-native');
const {
  JDDevice,
  JDTouchable,
  JDImage,
  JDViewPager,
  JDText
} = require('@areslabs/jdreact-core-lib');

const BANNERS = {
  section1: {
    "bannerId": 4686,
    "imgUrl": "https://img30.360buyimg.com/njmobilecms/jfs/t3187/78/2902161405/46549/af9d93d1/57e7dea2N384f1a2f.jpg",
    "linkUrl": "https://sale.jd.com/m/act/cvJgdk3mbf7.html",
  },
  section2: {
    "bannerId": 4694,
    "imgUrl": "https://img30.360buyimg.com/njmobilecms/jfs/t3142/277/2531782606/27298/32f7ec49/57e346ebN5082df8d.jpg",
    "linkUrl": "https://1.m.jd.com/detail/next?itemId=1300000000000119106",
  },
  section3: {
    "bannerId": 4696,
    "imgUrl": "https://img30.360buyimg.com/njmobilecms/jfs/t3169/298/3884728848/81711/3d4bf5e5/57f9a8f4Nde49b930.jpg",
    "linkUrl": "https://1.m.jd.com/detail/next?itemId=1300000000000119106",
  },
  section4: {
    "bannerId": 5694,
    "imgUrl": "https://img30.360buyimg.com/njmobilecms/jfs/t3175/342/3824191670/121858/23170ef1/57f9a933N1711e84f.jpg",
    "linkUrl": "https://1.m.jd.com/detail/next?itemId=1300000000000119106",
  },
};

class ArrayViewPager extends React.Component {
  static defaultProps = function() {
    let dataSource = new JDViewPager.DataSource({
      pageHasChanged: (p1, p2) => p1 !== p2,
    });
    return {
      initPage: 1,
      dataSource: dataSource.cloneWithPages(BANNERS, ['section1', 'section3', 'section4'])
    };
  }();

  state = {
    pageNow: this.props.initPage
  };

  render() {
    return (
      <View style={styles.wrapper}>
        <JDText>DataSource为对象的用法</JDText>
        <JDViewPager
          style={styles.viewPager}
          dataSource={this.props.dataSource}
          renderPage={this._renderPage}
          isLoop={true}
          autoPlay={true}
          initPage={1}
          onChangePage={this._onChangePage}
          renderPageIndicator={false}
        />
        <JDText>
          <JDText>pageNow: </JDText>
          <JDText>{this.state.pageNow}</JDText>
        </JDText>
      </View>
    );
  }

  _renderPage = (data) => {
    return (
      <JDTouchable style={styles.bannerItem}>
        <JDImage style={styles.bannerImage} source={{uri: data.imgUrl}} />
      </JDTouchable>
    );
  };

  _onChangePage = (pageNumber) => {
    this.setState({
      pageNow: pageNumber
    });
  };
}

const BANNER_HEIGHT = JDDevice.width * 200 / 640;
const styles = StyleSheet.create({
  wrapper: {
    marginBottom: JDDevice.getRpx(40),
  },
  viewPager: {
    width: JDDevice.width,
    height: BANNER_HEIGHT,
    overflow: 'hidden',
  },
  bannerItem: {
    flex: 1
  },
  bannerImage: {
    width: JDDevice.width,
    height: BANNER_HEIGHT,
    resizeMode: 'stretch',
  }
});

module.exports = ArrayViewPager;
